# GameManager.gd
extends Node

var current_score: int = 0
var game_time: float = 0.0
var is_game_over: bool = false
var is_paused: bool = false

var current_level_scene: Node = null
var current_level_index: int = 0 # Or use names
var level_order: Array[String] = [
	"res://scenes/levels/Level_Desert.tscn",
	"res://scenes/levels/Level_Forest.tscn",
	"res://scenes/levels/Level_SnowMountain.tscn",
	"res://scenes/levels/Level_Volcano.tscn",
	"res://scenes/levels/Level_Chaos.tscn"
]

var player_node: Node = null # Reference set externally (e.g., by MainGame scene)

@onready var game_timer: Timer = Timer.new()

func _ready():
	# Connect to own signals or others if needed
	SignalBus.enemy_died.connect(_on_enemy_died)
	SignalBus.player_died.connect(_on_player_died)
	SignalBus.boss_defeated.connect(_on_boss_defeated)

	add_child(game_timer)
	game_timer.wait_time = 1.0
	game_timer.timeout.connect(_on_game_timer_timeout)
	print("GameManager Ready")


func start_game():
	print("Starting New Game")
	current_score = 0
	game_time = 0.0
	is_game_over = false
	is_paused = false
	current_level_index = 0
	# Reset player stats (handled in player script or here)
	SignalBus.emit_signal("score_updated", current_score)
	SignalBus.emit_signal("time_updated", format_time(game_time))

	# Transition to the first level scene (handled by SceneManager or MainMenu)
	# For now, assume MainGame scene handles loading the first level
	# load_level(level_order[current_level_index]) # Example
	game_timer.start()


func set_player_node(p_node: Node):
	player_node = p_node
	print("Player node set in GameManager")


func pause_game():
	if is_game_over or is_paused:
		return
	is_paused = true
	get_tree().paused = true
	game_timer.paused = true
	SignalBus.emit_signal("game_paused")
	print("Game Paused")


func resume_game():
	if is_game_over or not is_paused:
		return
	is_paused = false
	get_tree().paused = false
	game_timer.paused = false
	SignalBus.emit_signal("game_resumed")
	print("Game Resumed")


func _on_game_timer_timeout():
	if not is_paused and not is_game_over:
		game_time += game_timer.wait_time
		SignalBus.emit_signal("time_updated", format_time(game_time))


func format_time(seconds: float) -> String:
	var minutes = floori(seconds / 60)
	var remaining_seconds = floori(fmod(seconds, 60))
	return "%02d:%02d" % [minutes, remaining_seconds]


func add_score(amount: int):
	if is_game_over: return
	current_score += amount
	SignalBus.emit_signal("score_updated", current_score)


func _on_enemy_died(_position: Vector2, _experience_yield: int, _enemy_type: String):
	# Basic scoring, could be more complex based on enemy type
	add_score(10)


func _on_player_died():
	if is_game_over: return
	print("Game Over triggered by player death")
	is_game_over = true
	game_timer.stop()
	get_tree().paused = true # Pause the tree to stop gameplay processing
	SignalBus.emit_signal("game_over")
	# Show Game Over screen (handled by UI manager or MainGame scene)


func _on_boss_defeated(_boss_name: String):
	print("Boss defeated: %s" % _boss_name)
	# Logic to proceed to the next level
	current_level_index += 1
	if current_level_index < level_order.size():
		load_level(level_order[current_level_index])
	else:
		# Game Won!
		print("All bosses defeated! Game Won!")
		is_game_over = true # Or trigger a specific win state
		game_timer.stop()
		get_tree().paused = true
		SignalBus.emit_signal("game_over") # Or a specific game_won signal


func load_level(level_path: String):
	print("GameManager attempting to load level:", level_path)
	# This function might be called by the MainGame scene,
	# which actually performs the scene switching.
	# This GameManager function mainly tracks the state.
	var level_name = level_path.get_file().get_basename().replace("Level_", "")
	SignalBus.emit_signal("level_loaded", level_name)
	# Reset level-specific timers or states if needed


func get_game_time() -> float:
	return game_time

func get_score() -> int:
	return current_score

func get_level_time_modifier() -> float:
	# Used by spawner for difficulty scaling
	# Example: Increase modifier every minute
	return 1.0 + floor(game_time / 60.0) * 0.1